<?
require("../../common/init.php");
require("author.php");
require("upfile.php");
require(ROOT."common/image_zoom.php");

$gee=$document; // gee, 意为赶车时候喊的"驾", 此处用来表示次页面的主角对象
$cate=$document_category; // cate = category, 分类
$gee_tags = $tags;
$gee_tag_list = $tag_list;
$cateid=isset($_GET["cid"])?clean($_GET["cid"]):0;

$title=ROOT_DOCUMENT_MANAGEMENT;
$top_cate=$cate->get_row($cateid);
$title=$top_cate['name_'.$lang];
$has_pic=$top_cate['has_pic']; // 分类下文章是否需要图片 need pic or not
$pic_height=$top_cate['pic_height'];
$pic_width=$top_cate['pic_width'];

$url='document';
$do=isset($_GET["do"])?clean($_GET["do"]):'view'; // 操作: 查看/编辑/删除 
$action=isset($_POST["action"])?clean($_POST["action"]):''; // 数据库操作: CURD 
$id=0; if (isset($_GET["id"])) $id = clean($_GET["id"]);
$page=1; if(isset($_GET["page"]))if(is_numeric($_GET["page"]))$page=$_GET["page"];

// sql action / sql 动作
switch ($action){
	case "update":
		sql_update();
		break;
	case "add":
		sql_insert();
		break;
    case "deletes": sql_deletes(); break;
    case "tags_add": sql_tags_add(); break;
}

$in_array=array();
$arr_cate=array();
$tem=$cate->get_rows(32,'parent_category_id',$cateid);
foreach ($tem as $val) {
	$in_array[]=$val['id'];
	$arr_cate[$val['id']]=$val;
}

$tag_list_info = $gee_tags->get_rows(1024, 'type', 2);
if($id==0){
	$order='seq_no';
	$where=array();
	$where[]=array('name'=>'category_id','val'=>$in_array, 'opn'=>'in');
	$pages=$gee->count_pages($where);
	$info=$gee->get_page($page,$where,$order);
}
else{
    $info=$gee->get_row($id);
    $where = array();
    $where[]=array('name'=>'p_id','val'=>$id);
    $where[]=array('name'=>'tags_table','val'=>3);
    $tag = $gee_tag_list->get_rows_advanced(1024, $where);
    $arr_tag = array();
    for($i = 0; $i < count($tag); $i++){
        $tag_info = $gee_tags->get_row($tag[$i]['tag_id']);
        $tag[$i]['tag_name'] = $tag_info['name_'.$lang];
        $arr_tag[] = $tag[$i]['tag_id'];
    }
    $str_tag = implode(',', $arr_tag);
}


function add()
{
	global $h, $url;
	$row = array(
	);
	echo $h->form($url.'.php', 1, '');
	show_box($row, true, true);
	echo $h->hidden('action', 'add');
	echo $h->former();
}
function update($info)
{
	global $gee, $h, $url, $id;
	if($id=="")
	{
		echo "Invali argument!!!";
		exit;
	}
	echo $h->form($url.'.php', 1, '');
  	show_box($info, true, false);
	echo $h->hidden('action', 'update');
	echo $h->former();
}
function delete($id)
{
	global $gee,$url, $gee_tags, $gee_tag_list;
    $where = array();
    $where[]=array('name'=>'p_id','val'=>$id);
    $where[]=array('name'=>'tags_table','val'=>3);
    $tag_list_arr = $gee_tag_list->get_rows_advanced(1024, $where);
	$picdir=ROOT.'upload/';
	$info=$gee->get_row($id);
	$oldpic=$picdir.$info['pic'];
	if($gee->delete($id)){
        foreach($tag_list_arr as $key => $val){
            $gee_tag_list->delete($val['id']);
            $count = $gee_tags->get_row($val['tag_id']);
            $tag_arr = array('count' => $count['count'] - 1);
            $gee_tags->update($tag_arr, 'id', $val['tag_id']);
        }
		@unlink($oldpic);
		wheel("$url.php");
	}
}	
function show_info($info)
{
	global $id;
	if($id==0)
	{
  	show_boxes($info);
	}
	else 
	{
		show_box($info, false);
	}
}
function sql_insert()
{
	global $gee,$cate,$url,$arrlang, $gee_tags, $gee_tag_list;
    $tag_list_str = isset($_POST['tag_list_str']) ? $_POST['tag_list_str'] : '';
    $tag_list_str_2_arr = explode(',', $tag_list_str);
	$cateid=$_POST["cid"];
	$page=$_POST["page"];

	$top_cate=$cate->get_row($cateid);
	$arr=array(
		'category_id'=>$_POST["category_id"],
		'language_id'=>$_POST["language_id"],
		'seq_no'=>$_POST["seq_no"],
		'name'=>$_POST["name"],
		'content'=>$_POST["content"],
		'keyword'=>$_POST["keyword"],
		'description'=>$_POST["description"],
	);
	// 附加字段
	for($i=1;$i<4;$i++){
		if($top_cate['has_field'.$i]) $arr['field'.$i]=$_POST['field'.$i];
    }
    // 图片
	if($_FILES["cpic"]["size"] > 0){
		$tem=$cate->get_row($cateid);
		$pic_width=$tem['pic_width'];
		$pic_height=$tem['pic_height'];

		$pic=upfile($_FILES["cpic"]);
		$upload_folder=ROOT.'upload/';
		//$image_resize=new Image_resize($upload_folder.$pic,$pic_width,$pic_height,1,$upload_folder.$pic);
		image_zoom($upload_folder.$pic, $upload_folder.$pic,$pic_width,$pic_height,IMAGE_BACKGROUND);
		$arr['pic']=$pic;
	}
	//pre($arr); exit;
	if($gee->insert($arr)){
        $id=$gee->get_last_insert_id();
        foreach($tag_list_str_2_arr as $key => $val){
            $tag_insert_arr=array(
                'tag_id' => $val,
                'p_id'=>$id,
                'tags_table' => 3,
            );
            $gee_tag_list->insert($tag_insert_arr);
            $count = $gee_tags->get_row($val);
            $tag_arr = array('count' => $count['count'] + 1);
            $gee_tags->update($tag_arr, 'id', $val);
        }
        yell(ROOT_SUCCESS,"$url-$cateid-p$page.html");
    }
}
function sql_update()
{
	global $gee,$cate,$url,$arrlang, $gee_tags, $gee_tag_list;
    $id=$_POST["id"];
    $tag_list_str = isset($_POST['tag_list_str']) ? $_POST['tag_list_str'] : '';
    $tag_list_str_2_arr = explode(',', $tag_list_str);
    $where = array();
    $where[]=array('name'=>'p_id','val'=>$id);
    $where[]=array('name'=>'tags_table','val'=>3);
    $tag_list_arr = $gee_tag_list->get_rows_advanced(1024, $where);
//    $tag_list_arr = $gee_tag_list->get_rows(1024, 'p_id', $id);
    $tag_same = array();
    foreach($tag_list_arr as $key => $val){
        if(in_array($val['tag_id'], $tag_list_str_2_arr)){
            $tag_same[] = $val['tag_id'];
        }
    }

	$cateid=$_POST["cid"];
	$page=$_POST["page"];

	$top_cate=$cate->get_row($cateid);
	$candelete=0;
	$upload_folder=ROOT.'upload/';
	$arr=array(
		'category_id'=>$_POST["category_id"],
		'language_id'=>$_POST["language_id"],
		'seq_no'=>iso($_POST["seq_no"]),
		'name'=>$_POST["name"],
		'content'=>$_POST["content"],
		'keyword'=>$_POST["keyword"],
		'description'=>$_POST["description"],
	);
	// 附加字段
	for($i=1;$i<4;$i++){
		if($top_cate['has_field'.$i]) $arr['field'.$i]=$_POST['field'.$i];
    }
    // 图片
	if($_FILES["cpic"]["size"]>0) { // 更新图片
		$info=$gee->get_row($id);
		$old_pic=$upload_folder.$info['pic'];
		$candelete=1;

		$pic=upfile($_FILES["cpic"]);
		$tem=$cate->get_row($cateid);
		$pic_width=$tem['pic_width'];
		$pic_height=$tem['pic_height'];

		//$image_resize=new Image_resize($upload_folder.$pic,$pic_width,$pic_height,1,$upload_folder.$pic);
		image_zoom($upload_folder.$pic, $upload_folder.$pic,$pic_width,$pic_height,IMAGE_BACKGROUND);
		$arr['pic']=$pic;
	}
    foreach($tag_list_arr as $key => $val){
        if(!in_array($val['tag_id'], $tag_same)){
            $gee_tag_list->delete($val['id']);
            $count = $gee_tags->get_row($val['tag_id']);
            $tag_arr = array('count' => $count['count'] - 1);
            $gee_tags->update($tag_arr, 'id', $val['tag_id']);
        }
    }
    foreach($tag_list_str_2_arr as $key => $val){
        if(!in_array($val, $tag_same)){
            $tag_insert_arr=array(
                'tag_id' => $val,
                'p_id'=>$id,
                'tags_table' => 3,
            );
            $gee_tag_list->insert($tag_insert_arr);
            $count = $gee_tags->get_row($val);
            $tag_arr = array('count' => $count['count'] + 1);
            $gee_tags->update($tag_arr, 'id', $val);
        }
    }
	if($gee->update($arr, 'id', $id ) ) {
		if($candelete)@unlink($oldcpic);
		yell(ROOT_SUCCESS,"$url-$cateid-p$page.html");
		exit;
	}
	wheel("$url-$cateid-p$page.html"); 
}

function sql_deletes(){
    global $gee,$page,$url, $gee_tag_list, $gee_tags;
    $page=iso(@$_POST["page"]);
    $s=iso(@$_POST["s"]);
    $filter=iso(@$_POST["filter"]);
    $all=$_POST["all"];
    $arrdelete=array();
    if(count($all)>0){
        foreach($all as $a){
//            $arrdelete[]=$a;
            $tag_list_arr = $gee_tag_list->get_rows(1024, 'p_id', $a);
            $upload_folder=ROOT.'upload/';
            $info=$gee->get_row($a);
            $old_pic_small=$upload_folder.$info['small_pic'];
            $old_pic_large=$upload_folder.$info['large_pic'];
            if($gee->delete($a)){
                foreach($tag_list_arr as $key => $val){
                    $gee_tag_list->delete($val['id']);
                    $count = $gee_tags->get_row($val['tag_id']);
                    $tag_arr = array('count' => $count['count'] - 1);
                    $gee_tags->update($tag_arr, 'id', $val['tag_id']);
                }
                @unlink($old_pic_small);
                @unlink($old_pic_large);
            }
        }
    }
//    if($gee->delete_rows($arrdelete))
    wheel($url.'.php?filter='.$filter.'&s='.$s.'&page='.$page);
}

function sql_tags_add(){
    global $gee,$page,$url, $gee_tag_list, $gee_tags;
    $page=iso(@$_POST["page"]);
    $s=iso(@$_POST["s"]);
    $filter=iso(@$_POST["filter"]);
    $all=$_POST["all"];
    $arrdelete=array();
    $tag_list_str = isset($_POST['tag_list_str']) ? $_POST['tag_list_str'] : '';
    $tag_list_str_2_arr = explode(',', $tag_list_str);
    if(count($all)>0){
        foreach($all as $a){
            $where = array();
            $where[]=array('name'=>'p_id','val'=>$a);
            $where[]=array('name'=>'tags_table','val'=>3);
            $tag_list_arr = $gee_tag_list->get_rows_advanced(1024, $where);
            $tag_same = array();
            foreach($tag_list_arr as $key => $val){
                if(in_array($val['tag_id'], $tag_list_str_2_arr)){
                    $tag_same[] = $val['tag_id'];
                }
            }
            foreach($tag_list_str_2_arr as $key => $val){
                if(!in_array($val, $tag_same)){
                    $tag_insert_arr=array(
                        'tag_id' => $val,
                        'p_id'=>$a,
                        'tags_table' => 3,
                        'user_id' => decrypt($_COOKIE['userid'])
                    );
                    $gee_tag_list->insert($tag_insert_arr);
                    $count = $gee_tags->get_row($val);
                    $tag_arr = array('count' => $count['count'] + 1);
                    $gee_tags->update($tag_arr, 'id', $val);
                    unset($tag_insert_arr);
                    unset($tag_arr);
                }
            }
            unset($where);
            unset($tag_same);
        }
    }
}
// view 加载视图
require ROOTVIEW.$url.'.php';

// end article.php